/**
 * Created by Administrator on 2016/5/18.
 *
 *TableData({
 *	gaine: id,
 *  table: 表格id,
 *	column: 表格头部数据，
 *	url: 后台表格数据json地址
 *	button： 按钮，
 *	operation: 操作按钮执行请求地址,
 *	type: 类型 0默认什么都有 1 二级表格数据（暂时两种）,
 *	success : 表格数据加载完成后执行回调事件，
 *})
 */
;(function(){
    var $_ = function(){};
    TableData = function(params){
        var columnsData = [];
        var condition = new Array();
        var gaine = params.gaine || '',
	        column = params.column || '',
	        url = params.url  || '',
	        operation = params.operation  || '',
	        success = params.success || function(){},
	        table = params.table || "example",
	        type = params.type || 0,
	        datas = params.datas||'';
        // 去除 多余“
        
        for(var i=0;i<column.length;i++){
        	condition[i] = new Array();
        	for(var key in column[i]){
        		if(key == "render"){
        			condition[i] = {"targets":i,"render":column[i][key],"orderable":column[i]["orderable"]};
    			}
        		else if(key == "visible"){
        			condition[i] = {"targets":i,"visible":column[i]["visible"],"searchable":column[i]["searchable"],};
            	}
        	}
        }
      
        // 表格框架生成
        person.generate(gaine,table);
        //表格头部
        person.TheadData(column,columnsData,table);
       
        //表格初始化
        $("#"+table).DataTable().destroy();
        // 表格数据生成
        person.sDataTable(url,columnsData,table,type,success,condition,datas);
        
        // 自适应 表格赋值 
        $("#"+table).width('100%');
        
        // 回调执行数据调用
        person.dataCall(table,columnsData);
        
        //自定义 模块生成        
        person.addTo(gaine,table);
        // 按钮点击事件
        person.Click(operation,table);
        
    };
    $_.prototype = {
        generate : function(gaine,table){
            var _Table ='<table id="'+table+'" class="table table-striped table-bordered table-advance table-hover"></table>',
                _Thead = '<thead></thead>',
                _Tbody = '<tbody></tbody>';

            $('#'+gaine).append(_Table);
            $("#"+table).append(_Thead);
            $("#"+table).append(_Tbody);
        },
        sDataTable : function(url,columnsData,table,type,success,condition,datas){
            var logon = '<img src="images/loading.gif"/>',
                nonumber =  '<img src="images/nonumber.png"/>';
            var init = {
                    "processing": true,// 服务器处理模式
                    "serverSide": true,//
                    "bPaginate": true,
                    "ordering":true,
                    "destroy":true,//摧毁	实例
                    "bInfo": true,
                    deferRender:true,
                    ajax:{
                        url:url,
                        "dataSrc": function (data) {
                            return data.data;
                        }
                    },
                    columns:columnsData,
                    language: {
                        "sProcessing": logon,
                        "sLengthMenu": "显示 _MENU_ 数据",
                        "sZeroRecords": "没有匹配结果",
                        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                        "sInfoPostFix": "",
                        "sSearch": "搜索:",
                        "sUrl": "",
                        "sEmptyTable": "没有查到你想要的数据",
                        "sLoadingRecords": logon,
                        "sInfoThousands": ",",
                        "oPaginate": {
                            "sFirst": "首页",
                            "sPrevious": "上页",
                            "sNext": "下页",
                            "sLast": "末页"
                        },
                        "oAria": {
                            "sSortAscending": ": 以升序排列此列",
                            "sSortDescending": ": 以降序排列此列"
                        }
                    },
                    rowId:'id',
                    columnDefs:condition,
                    dom:'<".top" and <"t_left" and> <".t_right" fl>>rt<".page" ip>',
                    initComplete:function(data){
                    	// 表格数据加载完后执行回调
                    	success();   
                	}
                }
            if(datas!==''){
//            	console.log(datas);
            	init.ajax["data"] = function(d){
                	$.each(datas,function(i,n){
                		d[n.name] = n.value;
                	})
                }
            }
            if(type === 1){
            	 _DataTable_down = $("#"+table).DataTable(init);
            	 $('#pagingTable').find('.top').remove();
            }else{
            	_DataTable = $("#"+table).DataTable(init);
            }
            
        },
        TheadData:function (data,columnsData,table) {
            var _Tr = '<tr></tr>';
            $("#"+table).find('thead').append(_Tr);
            for(i = 0, num = data.length; i < num; i++){
                columnsData[i] = {data:""};
                $("#"+table).find('thead').find('tr').append("<th>" + data[i].name + "</th>");
                createJson("data",data[i].colkey,columnsData[i]);
            }
            return columnsData;
        },
        addTo:function(gaine,table){
            var xinz = $('.doc-buttons button').prop("outerHTML");
            var seaCH = '<div class="form-group clearfix">'+
                '<input class="pull-left input-medium ui-autocomplete-input" id="'+table+'AccountName" name="userFormMap.accountName">'+
                '<a href="javascript:void(0)" class="pull-right fa fa-fw fa-search" id="'+table+'SearCh"></a>'+
                '</div>';
            $('.panel-heading').remove();
            $("#"+gaine+" .top .t_left").append(xinz);
            $("#"+gaine+" .top .t_right").append(seaCH)
        },
        Click:function(operation,table){
        	$("#"+table+"_wrapper").on('click','#'+table+'SearCh',function(){
            // 表格搜索自定义
        		_DataTable.search($('#'+table+'AccountName').val()).draw();
            });
           
            // 表格重绘完成后执行事件
            $('#'+table).on( 'draw.dt', function () {
            	CallBack();
            } );
            
        	$(document).on('keyup',"input[type=text].sequenceLimit",function(){
        		// 下拉顺序  值过滤及限制
        		$(this).val($(this).val().replace(/\D|^/g,''));
        		if($(this).val().length > 11){
        			$(this).val($(this).val().substring(0,11));
        		}
        	})
        },
        dataCall : function (table,columnsData){
            // 表格数据刷新执行事件
        	CallBack = function(){
	           	 for(var i=0;i<$("table tbody tr").length;i++){
	                 var id = $("table tbody tr").eq(i).attr('id');
	                 $("table tbody tr").eq(i).attr('dataId',id);
	                 $("table tbody tr").eq(i).removeAttr('id');
	             }
	        	 var TaBle = $('table tbody tr');
	        	 TaBle.each(function(index){
	        		 for(var i = 0; i < columnsData.length; i++){
	        			 $(this).find('td').eq(i).attr('name',columnsData[i].data);
		        	 }
   				 }); 
	        	 $("#user tbody tr").each(function(index){
					if($(this).find('td').eq(3).text() == "正常"){				
						$(this).find('td').eq( $(this).find('td').length - 1 ).find(".unfreezeFun").hide();
					}else{
						$(this).find('td').eq( $(this).find('td').length - 1 ).find(".leaveFun").hide();
					}
				 })
        	}
        }
    };
    // json 数据生成
    function createJson(prop, val,columns) {
        if(typeof val === "undefined") {
            delete columns[prop];
        }
        else {
            columns[prop] = val;
        }
    }
  
    // 点击后执行事件
    _click = function (operation,name,id,type) {
    	var type = type || 0;
        var perform =  {
            editFun: function  (id) {
                var url = operation + id;
                $.get(url,function(data){
                	layer.closeAll();
                	cover.closeAll();// 解除多次点击限制
                    layer.open({
                        title : "编辑",
                        type : 1,
                        area :  ["600px"] ,
                        content : data
                    });
                })
            },
            delFun:function (id) {
            	layer.closeAll();
                cover.closeAll();// 解除多次点击限制
                layer.confirm('是否删除？', function(index) {
                    var url = operation;
                    var s = CommnUtil.ajax(url, {
                        ids :id
                    }, "json");
                    if (s == "success") {
                        layer.msg('删除成功');
                        if(type === 0){
                        	_DataTable.ajax.reload(null, false);
                        }
                    } else {
                        layer.msg('删除失败');
                    }
                });
            },
            permissions:function (id){
                var url = operation + id;
                $.get(url,function(data){
                	 layer.closeAll();
                	cover.closeAll();// 解除多次点击限制
                    layer.open({
                        title : "分配权限",
                        type : 1,
                        area : ["600px"],
                        content : data
                    });
                })
            },
            addFun:function (){
                var url = operation;
                $.get(url,function(data){
                	layer.closeAll();
                	cover.closeAll();// 解除多次点击限制
                    layer.open({
                        title : "新增",
                        type : 1,
                        area : ["600px"],
                        content : data
                    });
                })
            },
            leaveFun:function (id){
            	layer.closeAll();
                cover.closeAll();// 解除多次点击限制
                layer.confirm('是否设置为冻结状态？', function(index) {
                    var url = operation;
                    var s = CommnUtil.ajax(url, {
                        ids :id
                    }, "json");
                    if (s == "success") {
                        layer.msg('设置成功');
                        _DataTable.ajax.reload(null, false);
                        $("#" +id ).remove();
                    } else {
                        layer.msg('设置失败');
                    }
                });
            },
            unfreezeFun:function (id){
            	layer.closeAll();
                cover.closeAll();// 解除多次点击限制
                layer.confirm('是否恢复正常状态？', function(index) {
                    var url = operation;
                    var s = CommnUtil.ajax(url, {
                        ids :id
                    }, "json");
                    if (s == "success") {
                        layer.msg('设置成功');
                        _DataTable.ajax.reload(null, false);
                        $("#" +id ).remove();
                    } else {
                        layer.msg('设置失败');
                    }
                });
            },
            editdropdownFun:function (id){
                var url = operation + id;  
                $.get(url,function(data){
                	layer.closeAll();
                	cover.closeAll();// 解除多次点击限制
                    layer.open({
                        title : "编辑下拉框",
                        type : 1,
                        area : ["650px","auto"],
                        content : data
                    });
                })

            },

        }
        // 按钮点击执行事件
    	switch (name){
    		case 'editFun':
    			var index = layer.load(0, {shade: false});
    			perform.editFun(id);
    			break;
    		case 'delFun':
    			var index = layer.load(0, {shade: false});
    			perform.delFun(id);
    			break;
    		case 'addFun':
    			var index = layer.load(0, {shade: false});
    			perform.addFun();
    			break;
    		case 'permissions':
    			var index = layer.load(0, {shade: false});
    			perform.permissions(id);
    			break;
    		case 'editdropdownFun':
    			var index = layer.load(0, {shade: false});
    			perform.editdropdownFun(id);
    			break;	
    		case 'leaveFun':
    			var index = layer.load(0, {shade: false});
    			perform.leaveFun(id);
    			break;
    		case 'unfreezeFun':
    			var index = layer.load(0, {shade: false});
    			perform.unfreezeFun(id);
    			break;
    	};
        
    }
    var person = new $_();
    
    var coverKernel=function(){};
    coverKernel.prototype = {
    	_Body:	function(){
    		$("body").append('<div class="cover"></div>')
    	},
    	closeAll: function(){
    		$("body .cover").remove()
    	}	
    }
    window.cover = new coverKernel();
})();